<?php
/**
 * Created by PhpStorm.
 * User: liyang
 * Date: 2017/4/26
 * Time: 9:38
 */

namespace App\Models;

use App\Libs\Tool\Impl\QueryResult;
use App\Libs\Tool\Impl\ReqToQueryAndParamImpl;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Log;

/**
 * 基础模型，目前包括参数查询、获取参数、获取保存参数、获取更新参数
 *
 * Class BaseModel
 * @package App\Models
 */
class BaseModel extends Model
{

    /**
     * 是否自动管理admin_id，只有在保存时有用
     * @var bool
     */
    protected $is_admin_id = false;

    /**
     * 是否自动管理时间戳，如果是true
     * @var bool
     */
    protected $is_timestamps = false;

    /**
     * 查询字段
     * @var array
     */
    protected $search_field = [];

    /**
     * 模糊查询字段
     * @var array
     */
    protected $vague_search_field = [];

    /**
     * 请求字段
     * @var array
     */
    protected $request_field = [];

    /**
     * 请求字段默认值
     * @var array
     */
    protected $request_field_default = [];

    /**
     * 是否启用状态字段
     * @var bool
     */
    protected $is_disable_state = false;

    /**
     * 状态字段
     * @var string
     */
    protected $state_field = 'state';

    /**
     * 状态值
     * @var array
     */
    protected $state_value = ['disable' => '0', 'enable' => '1'];

    /**
     * 多条件查询
     *
     * @param Request $request
     * @return array
     */
    public function queryAndParameters(Request $request) {
        $reqToQP = new ReqToQueryAndParamImpl($request, self::query());
        $reqToQP->add($this->search_field);
        $reqToQP->addVague($this->vague_search_field);
        return [
            'query'=>$reqToQP->getQuery(),
            'param'=>$reqToQP->getParam()
        ];
    }

    /**
     * 多条件查询
     *
     * @param Request $request
     * @return QueryResult
     */
    public function queryResult(Request $request) {
        $reqToQP = new ReqToQueryAndParamImpl($request, self::query());
        $reqToQP->add($this->search_field);
        $reqToQP->addVague($this->vague_search_field);
        return new QueryResult($reqToQP->getQuery(), $reqToQP->getParam());
    }

    /**
     * 简化queryResult
     *
     * @param Request $request
     * @param int $size
     * @param string $result_name
     * @return array
     */
    public function queryResultAuto(Request $request, $size = 10, $result_name = 'items') {
        $result = $this->queryResult($request);
        $resultArr = [
            $result_name => $result->query()->paginate($size),
            'param' => $result->param()
        ];
        return array_merge($resultArr, $result->param());
    }

    /**
     * 获取请求中的ID，根据主键
     *
     * @param Request $request
     * @return mixed|string
     */
    public function idByRequest(Request $request) {
        if($this->primaryKey == null) {
            Log::error('primaryKey is null.');
            return '';
        }
        $id = $request->get($this->primaryKey, '');
        if($id == null) {
            Log::error('$request->get is null.');
            return '';
        }
        return $id;
    }

    /**
     * 获取请求中的基础对象参数，不包含created_at、updated_at字段
     * 如果获取不到数据，字段将会被设置为''字符串，0不再此行列
     *
     * @param Request $request
     * @return array
     */
    public function requestToArray(Request $request) {
        $arr = [];
        foreach ($this->request_field as $item) {
            if(isEmpty($request->get($item, ''))) {
                try {
                    if(isEmpty($this->request_field_default[$item])) {
                        $arr[$item] = '';
                    } else {
                        $arr[$item] = $this->request_field_default[$item];
                    }
                } catch (\Exception $e) {
                    Log::error($e->getMessage());
                    $arr[$item] = '';
                }
            } else {
                $arr[$item] = $request->get($item, '');
            }

        }
        return $arr;
    }

    /**
     * 获取保存时使用的请求参数，增加created_at、updated_at字段
     *
     * @param Request $request
     * @return array
     */
    public function requestToArraySave(Request $request) {
        $arr = $this->requestToArray($request);
        if($this->is_timestamps) {
            $time = currentDateTime();
            $arr['created_at'] = $time;
            $arr['updated_at'] = $time;
        }
        if($this->is_admin_id) {
            $arr['admin_id'] = getAdmin()->id;
        }
        return $arr;
    }

    /**
     * 获取更新时使用的请求参数，增加updated_at字段
     *
     * @param Request $request
     * @return array
     */
    public function requestToArrayUpdate(Request $request) {
        $arr = $this->requestToArray($request);
        if($this->is_timestamps) {
            $arr['updated_at'] = currentDateTime();
        }
        return $arr;
    }

    /**
     * 根据请求获取参数添加对象
     *
     * @param Request $request
     * @return bool
     */
    public function addByRequest(Request $request) {
        try {
            $save_param = $this->requestToArraySave($request);
            return self::query()->insert([$save_param]);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return false;
        }
    }

    /**
     * 根据请求获取参数修改对象
     *
     * @param $id
     * @param Request $request
     * @return bool|int
     */
    public function updByRequest($id, Request $request) {
        try {
            $upd_param = $this->requestToArrayUpdate($request);
            return self::query()->where($this->primaryKey, $id)->update($upd_param);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return false;
        }
    }

    public function updByRequestAuto(Request $request) {
        $id = $this->idByRequest($request);
        if(!empty($id)) {
            return $this->updByRequest($id, $request);
        }
        Log::error('updByRequestAuto.$request.id is null.');
        return false;
    }

    /**
     * 删除一个对象根据ID
     *
     * @param $id
     * @return bool|int
     */
    public function del($id) {
        try {
            return self::query()->where($this->primaryKey, $id)->delete();
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return false;
        }
    }

    public function delAuto(Request $request) {
        $id = $this->idByRequest($request);
        if(!empty($id)) {
            return $this->del($id);
        }
        Log::error('delAuto.$request.id is null.');
        return false;
    }

    public function delList($ids) {
        if(empty($ids) || !is_array($ids)) {
            Log::error('delList ids is null.');
            return false;
        }
        try {
            return self::query()->whereIn($this->primaryKey, $ids)->delete();
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return false;
        }
    }

    /**
     * 默认禁用对象
     *
     * @param Request $request
     * @return bool|int
     */
    public function disable(Request $request) {
        $id = $this->idByRequest($request);
        if(!empty($id)) {
            return self::query()->where($this->primaryKey, $id)->update([
                $this->state_field => $this->state_value['disable']
            ]);
        }
        Log::error('disable.$request.id is null.');
        return false;
    }

    /**
     * 默认启用对象
     *
     * @param Request $request
     * @return bool|int
     */
    public function enable(Request $request) {
        $id = $this->idByRequest($request);
        if(!empty($id)) {
            return self::query()->where($this->primaryKey, $id)->update([
                $this->state_field => $this->state_value['enable']
            ]);
        }
        Log::error('disable.$request.id is null.');
        return false;
    }

}
